﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using SIMS.Shared.DTO;
using System;
using System.Collections.Generic;
using SIMS.Common.Models;
using SIMS.Common.RestClient;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Linq;
using SIMS.Shared.Models;

namespace SIMS.StudentModule.ViewModels
{
    public class AddEditStudentViewModel : BindableBase, IDialogAware
    {
        /// <summary>
        /// 班级实体
        /// </summary>
        private ClassesDTO? classes;

        public ClassesDTO? Classes
        {
            get { return classes; }
            set { SetProperty(ref classes, value); }
        }

        /// <summary>
        /// 班级列表
        /// </summary>
        private List<ClassesDTO> classess;

        public List<ClassesDTO> Classess
        {
            get { return classess; }
            set { SetProperty(ref classess, value); }
        }

        private StudentDTO student;

        public StudentDTO Student
        {
            get { return student; }
            set { student = value; }
        }

        private readonly HttpRestClient _httpClient;

        public AddEditStudentViewModel(HttpRestClient httpClient)
        {
            _httpClient = httpClient;
        }

        private DelegateCommand loadedCommand;

        public DelegateCommand LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new DelegateCommand(Loaded);
                }
                return loadedCommand;
            }
        }

        private async void Loaded()
        {
            this.Classess = new List<ClassesDTO>();
            var pagingModel = await GetClassess();
            if (pagingModel != null)
            {
                var entities = pagingModel.Items;
                Classess.AddRange(entities);

                if (student != null)
                {
                    this.Classes = Classess.FirstOrDefault(item => item.Id == student.ClassesId);
                }
            }
        }

        private async Task<PagingModel<ClassesDTO>?> GetClassess()
        {
            Dictionary<string, object?> parameters = new Dictionary<string, object?>();
            parameters["dept"] = null;
            parameters["grade"] = null;
            parameters["pageNum"] = 1;
            parameters["pageSize"] = 0;

            ApiRequest request = new()
            {
                Method = RestSharp.Method.Get,
                Parameters = parameters,
                Route = Api.CLASSES_GETCLASSESS
            };
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                var classes = JsonConvert.DeserializeObject<PagingModel<ClassesDTO>>(JsonConvert.SerializeObject(response.data));
                return classes;
            }
            return null;
        }

        private DelegateCommand cancelCommand;

        public DelegateCommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand(Cancel);
                }
                return cancelCommand;
            }
        }

        private void Cancel() {
            RequestClose?.Invoke((new DialogResult(ButtonResult.Cancel)));
        }

        private DelegateCommand saveCommand;

        public DelegateCommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new DelegateCommand(Save);
                }
                return saveCommand;
            }
        }

        private async void Save()
        {
            if (Student != null)
            {
                Student.CreateTime = DateTime.Now;
                Student.LastEditTime = DateTime.Now;
                if (Classes != null)
                {
                    Student.ClassesId = Classes.Id;
                    Student.ClassesName = Classes.Name;
                }
                bool flag;
                if (Student.Id > 0)
                {
                    flag = await UpdateStudent(Student);
                }
                else
                {
                    flag = await AddStudent(Student);
                }
                if (flag)
                {
                    RequestClose?.Invoke((new DialogResult(ButtonResult.OK)));
                }
                else
                {
                    //保存失败
                }
            }
        }

        private async Task<bool> AddStudent(StudentDTO student)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Post;
            request.Parameters = student;
            request.Route = Api.STUDENT_ADDSTUDENT;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> UpdateStudent(StudentDTO student)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Put;
            request.Parameters = student;
            request.Route = Api.STUDENT_UPDATESTUDENT;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        public string Title => "新增或编辑学生信息";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                var student = parameters.GetValue<StudentDTO>("student");
                this.Student = (StudentDTO)student.Clone();
            }
            else 
            { 
                this.Student = new StudentDTO();
            }
        }
    }
}
